package brain.mysql;



import brain.SqlConnection;
import java.sql.*;
import java.util.Map;
import java.util.TreeMap;

/*
 * MySql facilitator
 * by Martin Robinson
 * */

public class MySqlConnection implements SqlConnection{
	private final String _user,
	                      _pass,
	                      _url;
	private Connection _con;
	/**
	 * constructor
	 * @param usr  as user name String
	 * @param pass as password String
	 * @param url  as url string
	 * @throws ClassNotFoundException
	 */
	public MySqlConnection(final String usr, final String pass, final String url) throws ClassNotFoundException{
		Class.forName("com.mysql.jdbc.Driver");
		_user = usr;
		_pass = pass;
		_url = url;
	}

  @Override
  public void connect() throws SQLException {
      _con = DriverManager.getConnection(_url,_user,_pass);
  }

  @Override
  public void disconnect() throws SQLException {
      _con.close();
      _con=null;
  }
  
  @Override
  public boolean isConnected(){
    return _con!=null;
  }

  @Override
  	public void exec(final String sqlquery) throws SQLException{
		_con.createStatement().execute(sqlquery);
	}

  private Map makeMapFromRow(final ResultSet rs, final ResultSetMetaData md) throws SQLException{
    Map tmp = new TreeMap();
    for (int i=0;i<md.getColumnCount();i++){
      tmp.put(md.getColumnName(i),rs.getObject(i));
    }
    return tmp;
  }
    
    
  @Override
  public Map<CharSequence,Map> query(final String req) throws SQLException{
      ResultSet rs = _con.createStatement().executeQuery(req);
      ResultSetMetaData md = rs.getMetaData();
      Map tmp = new TreeMap();
      
      while(rs.next()){
        tmp.put(rs.getRow(), makeMapFromRow(rs,md));
      }
      
      return tmp;
	}

}
